<?php

namespace app\system\controller\system;

use app\common\controller\System;
use app\system\controller\finance\Payment;
use think\facade\Db;

/**
 * 文件管理
 *
 */
class Files extends System {

    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected array|string $quickSearchField = ['name'];

    public function initialize():void {
        parent::initialize();
        $this->model = new \app\system\model\system\Files;
    }

    public function getFileCategory(){
        $result = db::name('system_files_category')->order('id asc')->select();
        $this->success('', $result);
    }

    public function index():void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $params = $this->request->param();

        list($where, $alias, $limit, $order) = $this->queryBuilder();

        $this->withJoinTable = ['category'];
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where(['filter_id' => $this->filter['id']]);

        if(!empty($params['c1']) && empty($params['c2'])){
            $res = $res->where('FIND_IN_SET(' . $params['c1'] . ', category_ids)');
        }
        if(!empty($params['c1']) && !empty($params['c2'])){
            $res = $res->where('FIND_IN_SET(' . $params['c1'] . ', category_ids)')->where(['category_id' => $params['c2']]);
        }

        $res = $res->order($order)->paginate($limit);

        $list = $res->items();

        foreach($list as &$val){
            if($val['category'] && $val['category']['pid'] > 0){
                $val['category']['name'] = Db::name('system_files_category')->where(['id' => $val['category']['pid']])->value('name') . ' - ' . $val['category']['name'];
            }
        }

        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $data['filter_id'] = $this->filter['id'];
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\system\library\traits\Backend 中对应的方法至此进行重写
     */
}